from flask import Blueprint,request,jsonify
from db import db1
from comm import get_data
import re,time,random
import datetime
bp_handset = Blueprint("bp_handset",__name__)


@bp_handset.route('/sendSms',methods=['POST'])
def sendSms():
    #获取手机号
    data = get_data()
    mobile = data['mobile']
    if not mobile:
        return jsonify({'code':10011,'mes':'手机号不能为空'})
    #验证手机号是否合法
    res = re.match('^1[3-9]\d{9}$',data['mobile'])
    if not res:
        return jsonify({'code':10010,'mes':'手机号不合法'})
    #检验上次发送是否超过一分钟，1分钟之内不可重复发
    sql = "select stime from trecord where mobile='%s' order by id desc limit 1"%(str(mobile))
    record = db1.find(sql)
    if record:
        #判断时间是否在一分钟之内
        seconds = int(time.time())-int(record['stime'])
        if seconds<60:
            return jsonify({'code':10012,'mes':'一分钟之内不可重复发送'})
    #生成验证码，发送
    code = random.randint(100000,999999)
    #当发送成功写入记录表
    sql1 = "insert into trecord(mobile,code,stime) values('%s',%d,%d)"%(str(mobile),code,int(time.time()))
    db1.insert(sql1)
    #返回结果
    return jsonify({'code':200,'mes':'发送成功'})


@bp_handset.route('/tlogin',methods=['POST'])
def tlogin():
    #获取手机号验证码
    data = get_data()
    #通过手机号去记录表中查询，查最近的一条
    sql = "select code,stime from trecord where mobile='%s' order by id desc limit 0,1"%(data['mobile'])
    res = db1.find(sql)
    #验证码过期实践验证
    if not res:
        return jsonify({'code':10023,'mes':'手机号不存在'})
    if int(time.time())-int(res['stime'])>60:
        return jsonify({'code':10020,'mes':'验证码已经过期，请重新发送'})
    #验证是否相同
    if res['code'] == int(data['code']):
        #用户表中查询手机号是否存在
        sql1 = "select id from tuser where mobile='%s'"%(data['mobile'])
        user = db1.find(sql1)
        #存在返回登陆成功userid
        if user:
            return jsonify({'code':200,'userid':user['id'],'mes':'登陆成功'})
        #不存在添加新用户返回userid
        sql2 = "insert into tuser(mobile) values('%s')"%(data['mobile'])
        db1.insert(sql2)
        sql3 = "select id from tuser where mobile='%s'"%(data['mobile'])
        user3 = db1.find(sql3)
        return jsonify({'code':200,'userid':user3['id']})
    else:
        return jsonify({'code':10021,'mes':'验证码输入错误'})



#搜索接口
@bp_handset.route('/search')
def search():
    #获取数据
    title = request.args.get('title')
    #判断是否为空去掉空格
    title = title.strip()
    if not title:
        return jsonify({"code":10030,'mes':'搜索内容不能为空'})
    #判断长度 5-10
    if 1<=len(title)<=10:
        #数据库查询
        sql = "select * from goods where title like '%"+title+"%'"
        print(sql)
        res = db1.findall(sql)
        #写入记录表
        ip = request.remote_addr
        sql2 = "insert into grecord(title,ip) values('%s','%s')"%(title,ip)
        #返回结果
        db1.insert(sql2)
        return jsonify({"code":200,'list':res})
    else:
        return jsonify({"code":10031,'mes':'长度不合法'})

@bp_handset.route('/searches')
def searches():
    title = request.args.get('title')
    title = title.strip()
    sql = "select id,title from grecord where title like '%"+title+"%' order by id desc limit 0,5"
    res = db1.find_all(sql)
    return jsonify({'code':200,'list':res})


@bp_handset.route('/appraise',methods=['GET','POST'])
def appraise():
    if request.method == 'GET':
        id = request.args.get('id')
        if not id:
            sql = "select * from goods"
            res = db1.find_all(sql)
            return jsonify({'code':200,'list':res})
        else:
            sql = "select * from goods where id=%d"%(int(id))
            print(sql)
            res = db1.find(sql)
            return jsonify({'code':200,'list':res})
    else:
        data = get_data()
        if data['title']:
            sql1 = "insert into appraise(title,good_id) values('%s',%d)"%(data['title'],int(data['good_id']))
            db1.insert(sql1)
            return jsonify({'code':200})


@bp_handset.route('/authorM',methods=['POST'])
def author():
    data = get_data()
    try:
        username = data['username']
        password = data['password']
    except:
        return jsonify({'code':10010,'mes':'用户名或密码不能为空'})
    if not all([username,password]):
        return jsonify({'code':10010,'mes':'用户名或密码不能为空'})
    sql = "select * from author where username='%s'"%(username)
    res = db1.find(sql)
    if res:
        if res['password'] == password:
            return jsonify({"code":200,'mes':'登陆成功'})
        else:
            return jsonify({'code':10012,'mes':'用户名或密码错误'})
    else:
        return jsonify({'code':10011,'mes':'该用户不存在'})

@bp_handset.route('/booksM',methods=['GET','POST','DELETE','PUT'])
def booksM():
    if request.method == 'GET':
        username = request.args.get('username')
        sql = "select * from books where author_id=(select id from author where username='%s')"%(username)
        res = db1.find_all(sql)
        return jsonify({'code':200,'mes':res})
    elif request.method == 'DELETE':
        id = request.args.get('id')
        sql = "delete from books where id=%d"%(int(id))
        db1.insert(sql)
        return jsonify({'code':200,'mes':'删除成功'})
    elif request.method == 'POST':
        data = get_data()
        try:
            title = data['title']
            if not title:
                return jsonify({'code':20010,'mes':'标题不能为空'})
        except:
            return jsonify({'code':20011,'mes':'标题不能为空'})
        sql = "select id from books where title='%s'"%(title)
        res = db1.find(sql)
        if res:
            return jsonify({'code':20012,'mes':'标题不能重复'})
        else:
            ctime = datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d %H:%m:%S')
            sql = "insert into books(title,content,pic,author_id,ctime) values('%s','%s','%s',%d,'%s')"%(data['title'],data['content'],data['pic'],int(data['author_id']),ctime)
            db1.insert(sql)
            return jsonify({'code':200,'mes':'添加成功'})